package com.zn.opit.miniodemo.controller;

import com.zn.opit.miniodemo.domain.R;
import com.zn.opit.miniodemo.service.MinioService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

@RequestMapping(value = "file")
@RestController
public class FileController {

    @Resource
    private MinioService minioService;

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        String filename = minioService.upload(file);
        return R.ok().setData(filename);
    }

    @GetMapping("/preview/{filename}")
    public R preview(@PathVariable String filename) {
        String url = minioService.preview(filename);
        return R.ok().setData(url);
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<byte[]> download(@PathVariable String filename, HttpServletResponse response) {
        return minioService.download(filename, response);
    }

    @DeleteMapping("/delete")
    public void delete(@RequestParam("fileName") String fileName) {
        minioService.removeFiles(Collections.singletonList(fileName));
    }
}
